package ciyuan.Structure.MyFile;

import ciyuan.Block.BlockRegistryManager;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraftforge.fml.RegistryObject;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Iterator;

/**
 * @author 150149
 */
public class BlockInfo implements Externalizable {

    public BlockPos blockPos;
    public BlockState blockState;

    public BlockInfo(BlockPos blockPos, String blockName) {
        this.blockPos = blockPos;
        Iterator<Block> blockIterator = Registry.BLOCK.stream().iterator();
        while (blockIterator.hasNext()) {
            Block block = blockIterator.next();
            if (block.getDescriptionId().equals(blockName)) {
                blockState = block.defaultBlockState();
                return;
            }
        }
        Iterator<RegistryObject<Block>> blockIterator1 = BlockRegistryManager.BLOCKS.getEntries().iterator();
        while (blockIterator1.hasNext()) {
            RegistryObject<Block> blockRegistryObject = blockIterator1.next();
            if (blockRegistryObject.get().getDescriptionId().equals(blockName)) {
                blockState = blockRegistryObject.get().defaultBlockState();
                return;
            }
        }
        blockState = Blocks.AIR.defaultBlockState();
    }

    public BlockInfo(BlockPos blockPos, BlockState blockState) {
        this.blockPos = blockPos;
        this.blockState = blockState;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(blockPos.getX());
        out.writeInt(blockPos.getY());
        out.writeInt(blockPos.getZ());

        out.writeInt(Block.getId(blockState));
        out.writeUTF(blockState.getBlock().getDescriptionId());
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException {
        this.blockPos = new BlockPos(in.readInt(), in.readInt(), in.readInt());
        int id = in.readInt();
        String desName = in.readUTF();
        for (RegistryObject<Block> block : BlockRegistryManager.BLOCKS.getEntries()) {
            if (block.get().getDescriptionId().equals(desName)) {
                this.blockState = block.get().defaultBlockState();
                return;
            }
        }
        this.blockState = Block.stateById(id);
    }
}
